import general.AuctioneerClientInterface;
import general.Bid;
import general.ProductPrice;

import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.server.RemoteObject;
import java.util.UUID;
import java.util.Vector;

public class DutchAuctioneer extends Auctioneer {
	public Bid fStartingBid;
	public ProductPrice fDecreaseValue;

	public DutchAuctioneer(ProductPrice decreaseVal) throws IOException {
		super();
		fDecreaseValue = decreaseVal;
		fStartingBid = null;
	}

	public ProductPrice selectWinner() {
		fWinner = fStartingBid.getBidder();
		if (fWinner != null) {
			fBidders.remove(fWinner);
			return fStartingBid.getProductPrice();
		} else {
			return null;
		}
	}

	protected void newAuction() {
		fStatus = -1;
		fRunning = null;
		fBidders = new Vector<RemoteObject>();
		fWinner = null;
		fStartingBid = new Bid(fReq.getProductPrice(), null);
	}

	protected void updateBidders() {
		// Decrease StaringBid
		ProductPrice pp = new ProductPrice(fStartingBid.getProductPrice().getPrice() - fDecreaseValue.getPrice());
		fStartingBid = new Bid(pp, fStartingBid.getBidder());

		// Notify Bidders of updated Bit
		for (RemoteObject bidder : fBidders) {
			try {
				((AuctioneerClientInterface) bidder).updateBidders(fStartingBid);
			} catch (RemoteException e) {
				// Bidder unreachable
				System.out.println("UpdateBidders: Bidder Unreachable");
			}
		}
	}

	public void joinAuction(RemoteObject c, String name, UUID pID) throws RemoteException {
		if (fReq.getProductID() == pID) {
			fBidders.add(c);
		}
	}

	protected void cleanUp() {
		fRunning = null;
		fDecreaseValue = null;
		fStartingBid = null;
		fReq = null;
	}

	public void placeBid(Bid b) {
		if (b.isEqual(fStartingBid)) {
			fRunning.run();
			fStartingBid = b;
		}
	}

	public String getType() {
		return "Dutch Auction";
	}
}
